package com.tianji.learning.mq;

import com.tianji.api.dto.trade.OrderBasicDTO;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.utils.CollUtils;
import com.tianji.learning.service.ILearningLessonService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;



/**
 * @Description LessionChangeListerner
 * @Author dmx
 * @Date 2024-12-07
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class LessonChangeListener {

    /**
     * 优化：操作数据库的代码最好放到server层，
     */




    private final ILearningLessonService learningLessonService;
    /**
     * 监听购买课程之后mq发过来的消息，并将课程存储到learning_lesson表中
     * @param order
     */
    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = "learning.lesson.pay.queue"),
            exchange = @Exchange(name = MqConstants.Exchange.ORDER_EXCHANGE,
                    type = ExchangeTypes.TOPIC),
            key = MqConstants.Key.ORDER_PAY_KEY))
    public void listenerLessonPay(OrderBasicDTO order) {
       /*

       优化前

       //消息监听者的方法的参数列表的参数类型和消息发送者发送的消息的类型相同
        //1.接收支付完成之后的传过来的消息
        //获取对应id的课程列表
        List<CourseSimpleInfoDTO> simpleInfoList = courseClient.getSimpleInfoList(order.getCourseIds());
        //判断集合是否为空
        if (BeanUtils.isEmpty(simpleInfoList)){
            return;
        }
        List<LearningLesson> learningLessonList =new ArrayList<>();
        //遍历集合将数据填充
        for (CourseSimpleInfoDTO courseSimpleInfoDTO : simpleInfoList) {
            LearningLesson learningLesson = new LearningLesson();
            learningLesson.setCourseId(courseSimpleInfoDTO.getId());
            learningLesson.setUserId(order.getUserId());//获取用户的id
            learningLesson.setExpireTime(LocalDateTime.now().plusMonths(courseSimpleInfoDTO.getValidDuration()));
            learningLessonList.add(learningLesson);
        }
        //2.将课程信息填充之后插入数据库（需要填充的字段：user_id  course_id  expire_time）
        learningLessonService.saveBatch(learningLessonList);
    */

        //1.判断订单是否为空
        if (order==null || order.getOrderId()==null || CollUtils.isEmpty(order.getCourseIds())){
            log.error("接收到的mq消息为空，订单为空");
            return;
        }
        //2.添加课程
        learningLessonService.addUserLessons(order.getUserId(),order.getCourseIds());
    }
}
